package com.justech.mes.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


/**
 * @author feifei.li
 */
public class HttpClientUtils {
    /**
     * 发送post请求
     *
     * @param url        路径
     * @param jsonObject 参数(json类型)
     * @param encoding   编码格式
     * @return
     */
    public static String postJson(String url, JSONObject jsonObject, String encoding) {
        try {
            return postJson(url, jsonObject.toString(), new HashMap<>(0), encoding);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String postJson(String url, String data, Map<String, String> headers, String encoding) throws IOException {
        String body = "";

        /*创建httpclient对象*/
        CloseableHttpClient client = HttpClients.createDefault();
        /*创建post方式请求对象*/
        HttpPost httpPost = new HttpPost(url);

        /*装填参数*/
        StringEntity s = new StringEntity(data, "utf-8");
        s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json"));
        /*设置参数到请求对象中*/
        httpPost.setEntity(s);
        System.out.println("请求地址：" + url);

        /*设置header信息*/
        /*指定报文头【Content-type】、【User-Agent】*/
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        /*装填自定义header*/
        Set<String> keySet = headers.keySet();
        for (String key : keySet) {
            httpPost.setHeader(key, headers.get(key));
        }

        /*执行请求操作，并拿到结果（同步阻塞）*/
        CloseableHttpResponse response = client.execute(httpPost);
        /*获取结果实体*/
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            /*按指定编码转换结果实体为String类型*/
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        /*Release links*/
        response.close();
        return body;
    }
}
